import { computed, ref } from "vue";
import { defineStore } from "pinia";
import { useUserStore } from "./user";
import { insertCartAPI, findNewCartListAPI, delCartAPI } from "@/apis/cart";
export const useCartStore = defineStore(
  "cart",
  () => {
    const userStore = useUserStore();
    const isLogin = computed(() => userStore.userInfo.token);
    const cartList = ref([]);

    const addCart = async (goods) => {
      // 查看是否登录
      if (isLogin.value) {
        // 登陆之后加入购物车
        const { skuId, count } = goods;
        await insertCartAPI({ skuId, count });
        updateNewList();
      } else {
        const item = cartList.value.find((item) => goods.skuId === item.skuId);
        if (item) {
          item.count++;
        } else {
          cartList.value.push(goods);
        }
      }
      // goods是传过来的对象 cartlist查找
    };
    // 删除购物车
    const delCart = async (skuId) => {
      if (isLogin.value) {
        await delCartAPI([skuId]);
        updateNewList();
      } else {
        // 用splice方法删除
        //   const idx = cartList.value.findIndex((item) => skuId === item.skuId);
        //   cartList.value.splice(idx, 1);

        //   用filter方法删除
        cartList.value = cartList.value.filter((item) => skuId !== item.skuId);
      }
    };
    // 获取最新购物车列表action
    const updateNewList = async () => {
      const res = await findNewCartListAPI();
      cartList.value = res.result;
    };
    const allCount = computed(() =>
      cartList.value.reduce((a, c) => a + c.count, 0)
    );
    const allPrice = computed(() =>
      cartList.value.reduce((a, c) => a + c.count * c.price, 0)
    );
    // 选中的cart进行计算价格和商品
    const selectedCount = computed(() =>
      cartList.value
        .filter((item) => item.selected)
        .reduce((a, c) => a + c.count, 0)
    );
    const selectedPrice = computed(() =>
      cartList.value
        .filter((item) => item.selected)
        .reduce((a, c) => a + c.count * c.price, 0)
    );
    // 单选功能
    const singleCheck = (skuId, selected) => {
      const item = cartList.value.find((item) => skuId === item.skuId);
      item.selected = selected;
    };
    // 是否全选功能
    const isAll = computed(() => cartList.value.every((item) => item.selected));
    const allCheck = (selected) => {
      cartList.value.forEach((item) => (item.selected = selected));
    };
    // 清除购物车
    const clearCart = () => {
      cartList.value = [];
      console.log(cartList.value);
    };
    return {
      cartList,
      selectedCount,
      selectedPrice,
      addCart,
      delCart,
      allCount,
      allPrice,
      singleCheck,
      isAll,
      allCheck,
      clearCart,
      updateNewList,
    };
  },
  {
    persist: true,
  }
);
